package com.example.shop.service.impl;

import com.example.common.common.config.filter.UserContext;
import com.example.common.service.ImageManage;
import com.example.common.utils.Assert;
import com.example.shop.common.OrderStatus;
import com.example.shop.entity.*;
import com.example.shop.mapper.*;
import com.example.shop.model.req.CartSkuDTO;
import com.example.shop.model.req.CreateOrderDTO;
import com.example.shop.model.req.ModifyOrderDTO;
import com.example.shop.model.resp.OrderDetail;
import com.example.shop.model.resp.OrderItemDetail;
import com.example.shop.service.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author qwer3
 * @version 1.0.0
 * @create 2025/11/2 11:22
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final GoodsSkuMapper goodsSkuMapper;
    private final GoodsMapper goodsMapper;
    private final OrderItemMapper orderItemMapper;
    private final OrderMapper orderMapper;
    private final ShopMapper shopMapper;
    private final ImageManage imageManage;

    @Transactional
    @Override
    public void createOrder(CreateOrderDTO createOrderDTO) {
        // 查询店铺

        // 查询商品，sku
        List<CartSkuDTO> list = createOrderDTO.getList();
        if (createOrderDTO.isCart()) {
            // 批量处理
        } else {
            // 单个处理
        }

        String orderId = UUID.randomUUID().toString();
        List<OrderItem> orderItems = new ArrayList<>();
        Order order = new Order();
        long totalPrice = 0L;

        for (CartSkuDTO cartSkuDTO : list) {
            OrderItem orderItem = new OrderItem();
            String goodsId = cartSkuDTO.getGoodsId();
            String skuKey = cartSkuDTO.getSkuKey();
            GoodsSku goodsSku = goodsSkuMapper.queryGoodsSkuByGoodsIdWithSkuId(goodsId, skuKey);
            Assert.notNull(goodsSku, "商品不存在");
            Goods goods = goodsMapper.queryGoodsById(goodsId);

            long itemPrice = goods.getPrice() * cartSkuDTO.getQuantity();
            orderItem.setItemId(UUID.randomUUID().toString());
            orderItem.setOrderId(orderId);
            orderItem.setGoodsId(goodsId);
            orderItem.setSkuId(skuKey);
            orderItem.setNums(cartSkuDTO.getQuantity());
            orderItem.setItemPrice(itemPrice);
            orderItem.setShopId(goods.getShopId() != null ? goods.getShopId() : "xqtd");
            totalPrice += itemPrice;
            orderItems.add(orderItem);
        }

        order.setUserId(UserContext.getCurrentUser().getUserId());
        order.setTotalPrice(totalPrice);
        order.setOrderId(orderId);
        order.setStatus(OrderStatus.PAID);
        order.setAddressId("default");

        orderMapper.createOrder(order);
        orderItemMapper.batchCreateOrderItem(orderItems);
        System.out.println();
        // 查询库存

        // 生成订单

        // 扣除数量，保存数据库
    }

    @Override
    public List<OrderDetail> getOrderList() {
        String userId = UserContext.getCurrentUser().getUserId();
        List<Order> orderList = orderMapper.getOrderByUserId(userId);
        List<OrderItemDetail> orderItemDetailList = orderItemMapper.getOrderList(userId);

        // 1. 为每个订单项设置图片和价格（可保留）
        for (OrderItemDetail detail : orderItemDetailList) {
            String imageUrl = imageManage.getImageUrl(detail.getSkuImage());
            detail.setSkuImage(imageUrl);
        }

        // 2. 按订单 ID 分组
        Map<String, List<OrderItemDetail>> orderItemMap = orderItemDetailList.stream()
                .filter(item -> item.getShopCode() != null) // 排除 null
                .collect(Collectors.groupingBy(OrderItemDetail::getOrderId));

        // 3. 收集所有涉及的 shopCode（用于批量查询店铺）
        Set<String> allShopCodes = orderItemDetailList.stream()
                .map(OrderItemDetail::getShopCode)
                .collect(Collectors.toSet());

        // 4. 批量查询店铺信息
        Map<String, Shop> shopMap = new HashMap<>();
        if (!allShopCodes.isEmpty()) {
            List<Shop> shops = shopMapper.queryShopListById(new ArrayList<>(allShopCodes));
            shopMap = shops.stream()
                    .collect(Collectors.toMap(Shop::getShopId, shop -> shop));
        }

        // 5. 构建最终结果
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (Order order : orderList) {
            List<OrderItemDetail> itemsInOrder = orderItemMap.get(order.getOrderId());
            if (itemsInOrder == null || itemsInOrder.isEmpty()) {
                continue; // 跳过无订单项的订单
            }

            // 按 shopCode 对当前订单的 items 分组
            Map<String, List<OrderItemDetail>> itemsByShop = itemsInOrder.stream()
                    .filter(item -> item.getOrderId() != null)
                    .collect(Collectors.groupingBy(OrderItemDetail::getShopCode));

            for (Map.Entry<String, List<OrderItemDetail>> entry : itemsByShop.entrySet()) {
                String shopCode = entry.getKey();
                List<OrderItemDetail> shopItems = entry.getValue();

                Shop shop = shopMap.get(shopCode);
                if (shop == null) {
                    // 可选：处理店铺不存在的情况
                    continue;
                }

                long count = shopItems.stream().mapToLong(OrderItemDetail::getPrice).sum();
                OrderDetail orderDetail = OrderDetail.builder()
                        .orderId(order.getOrderId())
                        .items(shopItems)
                        .shopCode(shop.getShopId())
                        .shopName(shop.getShopName())
                        .status(order.getStatus().getStatus())
                        .createTime(order.getCreateTime())
                        .totalAmount(count)
                        .build();

                orderDetails.add(orderDetail);
            }
        }

        return orderDetails;
    }

    @Override
    public void modifyOrderStatus(ModifyOrderDTO modifyOrderDTO) {
        Order order = orderMapper.getOrderByOrderId(modifyOrderDTO.getOrderId());
        if (order == null) {
            throw new RuntimeException("订单不存在！");
        }

        OrderStatus newStatus = OrderStatus.getOrderStatus(modifyOrderDTO.getStatus());
        verifyOrderStatus(order, newStatus);
        orderMapper.modifyOrderStatus(order.getOrderId(), newStatus);
    }

    private void verifyOrderStatus(Order order, OrderStatus newStatus) {
        // OrderStatus.PENDING -> OrderStatus.PAID || OrderStatus.CANCELLED
        // OrderStatus.PAID -> OrderStatus.CANCELLED
        // OrderStatus.SHIPPED -> OrderStatus.RECEIVED

        OrderStatus orderStatus = order.getStatus();
        if (orderStatus.equals(OrderStatus.PENDING)) {
            Assert.isTrue(newStatus.equals(OrderStatus.PAID) || newStatus.equals(OrderStatus.CANCELLED),
                    "订单状态异常，请刷新后重试");
        } else if (orderStatus.equals(OrderStatus.PAID)) {
            Assert.isTrue(newStatus.equals(OrderStatus.CANCELLED), "订单状态异常，请刷新后重试");
        } else if (orderStatus.equals(OrderStatus.SHIPPED)) {
            Assert.isTrue(newStatus.equals(OrderStatus.RECEIVED), "订单状态异常，请刷新后重试");
        }
    }
}
